<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>归集设置</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-card class="never-card margin-b15" shadow="never">
            <div class="card-header">
              离职人员名单
            </div>
            <div class="card-body">
              <ul>
                <li v-for="datas in quitList" :key="datas.id">
                  <label><i class="fa fa-user" aria-hidden="true"></i> {{datas.userName}} </label>
                  <label><i class="fa fa-address-card" aria-hidden="true"></i> {{datas.userId}} </label>
                  <label><i class="fa fa-calendar" aria-hidden="true"></i> {{datas.date | filterTime }} </label>
                  <label data-clipboard-action="copy" class="copy" :data-clipboard-text="datas.userName" @click="copyLink">
                    <i class="fa fa-clipboard" aria-hidden="true"> 复制</i>
                  </label>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
           <el-card class="never-card margin-b15" shadow="never">
            <div class="card-header">
              调岗人员名单
            </div>
            <div class="card-body">
              <ul>
                <li v-for="items in mobilizeList" :key="items.id">
                   <label><i class="fa fa-user" aria-hidden="true"></i> {{items.userName}} </label>
                  <label><i class="fa fa-address-card" aria-hidden="true"></i> {{items.userId}} </label>
                  <label><i class="fa fa-calendar" aria-hidden="true"></i> {{items.date | filterTime }} </label>
                  <label data-clipboard-action="copy" class="copy" :data-clipboard-text="items.userName" @click="copyLink">
                    <i class="fa fa-clipboard" aria-hidden="true"> 复制</i>
                  </label>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
        <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <!-- 员工姓名 -->
            <el-form-item label="员工姓名">
              <!-- 员工选择框子组件 -->
              <!-- <user-sel :users="users" @seluser="selUser"></user-sel> -->
               <el-autocomplete
                v-model="formInline.userId"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入姓名"
                @select="handleSelect"
                clearable
              >
                <template slot-scope="{ item }">
                  <div class="selName">
                    <span>{{ item.userName }}</span>
                    <span>[{{ item.userId }}]</span>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="formInline.status">
                <el-option label="无" value=""></el-option>
                <el-option label="在职" value="0"></el-option>
                <el-option label="离职" value="1"></el-option>
              </el-select>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <!-- 批量设置 -->
          <el-button
            size="medium"
            icon="el-icon-setting"
            @click="batchRemove"
            v-if="btnAdd"
          > 设置</el-button>
          <!-- 归集结果 -->
          <el-button style="float:right;" type="success" icon="el-icon-position" @click="pushHandle" v-if="btnAdd">归集结果</el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="menusData"
          border
          @selection-change="selsChange"
          style="width: 100%"
          height="395"
          ref="menusData"
        >
          <!-- 全选 -->
          <el-table-column type="selection" width="40" fixed></el-table-column>
          <!-- 属地 -->
          <el-table-column prop="location" sortable label="属地" width="120"></el-table-column>
          <!-- 公司 -->
          <el-table-column
            :show-overflow-tooltip="true"
            sortable
            prop="ycompName"
            label="公司"
            width="150"
          ></el-table-column>
          <!-- 部门 -->
          <el-table-column
            :show-overflow-tooltip="true"
            sortable
            prop="ydeptName"
            label="部门"
            width="150"
          ></el-table-column>
            <!-- 上市部门 -->
          <el-table-column prop="position" label="岗位" :show-overflow-tooltip="true" width="120"></el-table-column>
          <!-- 工号 -->
          <el-table-column prop="userId" label="工号" width="120"></el-table-column>
          <!-- 姓名 -->
          <el-table-column prop="userName" label="姓名" width="120"></el-table-column>
          <!-- 上市部门 -->
          <el-table-column prop="deptName" sortable label="上市部门" :show-overflow-tooltip="true" width="150"></el-table-column>
          <!-- 口径 -->
          <el-table-column prop="typeName" sortable label="口径" width="120"></el-table-column>
          <!-- 项目 -->
          <el-table-column prop="proName" sortable label="项目" :show-overflow-tooltip="true" width="150"></el-table-column>
          <!-- 模块 -->
          <el-table-column prop="moduleName" sortable label="模块" :show-overflow-tooltip="true" width="150"></el-table-column>
        <!-- 级别 -->
          <el-table-column prop="level" sortable label="级别"></el-table-column>
          <el-table-column
            prop="status"
            label="标签"
            width="100"
            sortable
            filter-placement="bottom-end">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">已设置</el-tag>
              <el-tag v-else type="error">未设置</el-tag>
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="100"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <!-- 设置 -->
              <el-button size="mini" @click="editHandle(scope.row)" v-if="btnEdit"><i class="el-icon-setting"></i> 设置</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
      <!-- 弹窗 新增or修改 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
      <!-- 设置、批量设置表单 -->
        <el-form ref="editForm" :model="editForm" label-width="80px">
          <!-- 备注说明 -->
          <el-form-item label="口径设置" prop="note">
            <div style="padding-top:10px;">
              <el-tree
                ref="caltrees"
                :data="treeld"
                show-checkbox
                node-key="id"
                check-strictly
                default-expand-all
                @check-change="handleClick"
              >
              </el-tree>

               <el-tree
                v-show="false"
                ref="treehd"
                :data="treeld"
                show-checkbox
                node-key="id"
                default-expand-all
              >
              </el-tree>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 关闭弹窗 -->
          <el-button @click.native="dialogFormVisible=false">取消</el-button>
          <!-- 批量设置 清空表单初始数据 -->
          <el-button
            v-if="dialogStatus=='create'"
            type="primary"
            @click="createData"
          >批量设置</el-button>
          <!-- 设置 获取表单初始数据 -->
          <el-button v-else type="primary" @click="editData">设置</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';
import { _debounce } from '@/public/debounce.js';

export default {
  name: 'summarize',
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有员工
    this.getUsersAll();

    // 获取本月调岗员工
    this.getPostUsers();

    // 获取本月离职员工
    this.getQuitUsers();

    // 加载分页数据
    this.getmenusDataByPage();

    // 加载口径树数据
    this.getInfo();
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD');
    }
  },

  // 当前页面数据
  data () {
    return {
      // 离职人员列表
      quitList: [],
      // 调岗人员列表
      mobilizeList: [],

      calv: [],
      // 变更人员
      options: [],
      // 模块树
      treeld: [],
      // 当前选中ID
      selectId: [],
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取所有用户
      usersAll: [],

      // 检索匹配
      restaurants: [],
      state: '',
      timeout: null,

      // 搜索条件
      formInline: {
        userId: '',
        status: '0'
      },

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',

      // 弹窗标题
      textMap: {
        edit: '设置口径',
        create: '批量设置'
      },
      // 弹窗是否显示
      dialogFormVisible: false,

      // 列表选中列
      sels: [],

      // 界面默认数据
      editForm: {}
    };
  },

  mounted () {
    this.restaurants = this.loadAll();
  },

  methods: {
    // 获取所有员工数据
    getUsersAll () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          for (let i = datas.length; i--;) {
            _this.usersAll.push({
              compName: datas[i].compName,
              deptName: datas[i].deptName,
              userId: datas[i].userId,
              userName: datas[i].userName
            });
          };
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 加载全部员工数据
    loadAll () {
      return this.usersAll;
    },

    // 自动检索匹配
    querySearchAsync (queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? restaurants.filter(_this.createStateFilter(queryString)) : restaurants;
      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },

    // 查询
    createStateFilter (queryString) {
      return (state) => {
        return (state.userName.indexOf(queryString) === 0);
      };
    },

    // 选中赋值
    handleSelect (item) {
      this.formInline.userId = item.userId;
    },
    // 获取调岗人员
    getPostUsers () {
      let _this = this;
      let params = {
        type: 1,
        date: moment(new Date()).format('YYYY-MM')
      };
      _this.$http.post('api/findPersonnelList', params).then(res => {
        let {code, datas} = res;
        if (code === 0) {
          _this.mobilizeList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取离职人员
    getQuitUsers () {
      let _this = this;
      let params = {
        type: 2,
        date: moment(new Date()).format('YYYY-MM')
      };
      _this.$http.post('api/findPersonnelList', params).then(res => {
        let {code, datas} = res;
        if (code === 0) {
          _this.quitList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 快速复制
    copyLink () {
      let _this = this;
      let clipboardObj = new _this.$clipboard('.copy');
      clipboardObj.on('success', function () {
        return true;
      });
      clipboardObj.on('error', function () {
        return false;
      });
    },

    // 获取口径树信息
    getInfo () {
      let _this = this;
      // 获取树
      _this.$http.post('api/findLastTree').then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          let ctreeld = JSON.parse(datas.tree);
          _this.treeld = ctreeld;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 只能单选
    handleClick (data, checked, node) {
      let _this = this;
      if (checked) {
        _this.selectId.push(data.id);
        _this.$refs.caltrees.setCheckedKeys(_this.selectId.slice(-1));
        _this.$refs.treehd.setCheckedKeys([]);
        _this.$refs.treehd.setCheckedKeys([data.id]);
      }
    },

    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },

    // 显示编辑界面
    editHandle: function (row) {
      let _this = this;
      // 弹窗类型
      _this.dialogStatus = 'edit';
      // 弹窗显示状态
      _this.dialogFormVisible = true;
      // 弹出窗表单初始值赋值
      _this.editForm = Object.assign({}, row);
    },

    // 显示新增界面
    addHandle: function () {
      let _this = this;
      // 弹窗类型
      _this.dialogStatus = 'create';
      // 弹窗显示状态
      _this.dialogFormVisible = true;
      // 初始化新增界面默认数据
      _this.editForm = {};
    },

    // 归集结果
    pushHandle: function () {
      let _this = this;
      let params = {
        month: moment().month() + 1,
        year: moment().year()
      };
      // 提交归集结果
      _this.$http.post('api/insertColHis', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          _this.selHandle();
          _this.$message({
            message: '归集结果发送成功！',
            type: 'success'
          });
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询分页数据
    selHandle: function () {
      let _this = this;
      // 收集请求数据
      let params = {
        userId: _this.formInline.userId,
        status: _this.formInline.status,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 根据员工ID 查询分页数据
      _this.$http.raw('api/findUserColsByUserId', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 全选、单选、多选
    selsChange: function (sels) {
      this.sels = sels;
    },

    // 批量设置
    batchRemove: function () {
      let _this = this;
      // 判断是否选择数据
      if (!_this.sels.length) {
        _this.$message.warning('您还没选择任何数据！');
        return;
      }
      // 设置关联，批量插入
      _this.addHandle();
    },

    // 批量设置
    createData: _debounce(function () {
      let _this = this;

      let bdata = _this.$refs.treehd.getHalfCheckedNodes();
      let sdata = _this.$refs.treehd.getCheckedNodes();
      let params = [];

      bdata.map(item => {
        params.push(item.label);
      });

      sdata.map(key => {
        params.push(key.label);
      });

      let datas = [];

      for (let i = _this.sels.length; i--;) {
        let dobject = {
          id: _this.sels[i].id ? _this.sels[i].id : '',
          userId: _this.sels[i].userId,
          userName: _this.sels[i].userName,
          typeName: '', // 口径
          deptName: '', // 部门
          proName: '', // 项目
          moduleName: '', // 模块
          level: '', // 级别
          status: 1, // 设置状态 1已设置 0未设置
          note: '' // 备注说明
        };
        params.map(index => {
          if (index.indexOf('口径') !== -1) {
            dobject.typeName = index.substr(3, index.length);
          }
          if (index.indexOf('部门') !== -1) {
            dobject.deptName = index.substr(3, index.length);
          }
          if (index.indexOf('项目') !== -1) {
            dobject.proName = index.substr(3, index.length);
          }
          if (index.indexOf('模块') !== -1) {
            dobject.moduleName = index.substr(3, index.length);
          }
          if (index.indexOf('级别') !== -1) {
            dobject.level = index.substr(3, index.length);
          }
        });
        datas.push(dobject);
      };

      _this.$nextTick(() => {
        // 批量设置关联信息
        _this.$http.raw('api/batchCol', datas).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            _this.$message({
              message: '批量设置成功！',
              type: 'success'
            });
            // 初始化弹出窗表单数据
            _this.$refs['editForm'].resetFields();
            // 关闭弹窗
            _this.dialogFormVisible = false;
            // 刷新列表
            _this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      });
    }, 200),

    // 设置关联
    editData: _debounce(function () {
      let _this = this;

      let bdata = _this.$refs.treehd.getHalfCheckedNodes();
      let sdata = _this.$refs.treehd.getCheckedNodes();
      let params = [];

      bdata.map(item => {
        params.push(item.label);
      });

      sdata.map(key => {
        params.push(key.label);
      });

      let datas = [{
        id: _this.editForm.id ? _this.editForm.id : '',
        userId: _this.editForm.userId,
        userName: _this.editForm.userName,
        typeName: '', // 口径
        deptName: '', // 部门
        proName: '', // 项目
        moduleName: '', // 模块
        level: '', // 级别
        status: 1, // 设置状态 1已设置 0未设置
        note: '' // 备注说明
      }];

      params.map(index => {
        if (index.indexOf('口径') !== -1) {
          datas[0].typeName = index.substr(3, index.length);
        }
        if (index.indexOf('部门') !== -1) {
          datas[0].deptName = index.substr(3, index.length);
        }
        if (index.indexOf('项目') !== -1) {
          datas[0].proName = index.substr(3, index.length);
        }
        if (index.indexOf('模块') !== -1) {
          datas[0].moduleName = index.substr(3, index.length);
        }
        if (index.indexOf('级别') !== -1) {
          datas[0].level = index.substr(3, index.length);
        }
      });

      _this.$nextTick(() => {
        // 设置关联信息
        _this.$http.raw('api/batchCol', datas).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            _this.$message({
              message: '设置成功！',
              type: 'success'
            });
            // 初始化弹出窗表单数据
            _this.$refs['editForm'].resetFields();
            // 关闭弹窗
            _this.dialogFormVisible = false;
            // 刷新列表
            _this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      });
    }, 200),

    // 刷新页面数据
    getmenusDataByPage () {
      let _this = this;
      // 收集请求参数
      let params = {
        userId: _this.formInline.userId === null ? '' : _this.formInline.userId,
        status: _this.formInline.status === null ? '' : _this.formInline.status,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 获取分页数据
      _this.$http.raw('api/findUserColsByUserId', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
